package com.itheima.udp2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/*
udp接收端
 */
public class JieshouClient {

    public static void main(String[] args) throws IOException {
        //创建接受对象
        final DatagramSocket ds = new DatagramSocket(8888);
        //创建数据对象
        Runnable runnable = new Runnable() {
            public void run() {
                while (true) {
                    byte[] bytes = new byte[1024 * 64];
                    DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
                    // 接受
                    try {
                        ds.receive(dp);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //查看数据
                    //byte[] data = dp.getData();
                    int length = dp.getLength();
                    String s = new String(bytes, 0, length);
                    System.out.println(s);
                }
            }
        };
new Thread(runnable).start();
        //创建数据对象
        Runnable runnable1 = new Runnable() {
            public void run() {
                try {
                    while (true) {
                        String fasongs=new Scanner(System.in).nextLine();
                        byte[] s1 = fasongs.getBytes();
                        InetAddress ip = InetAddress.getByName("zhaichaojie");
                        int port =9999;
                        DatagramPacket fasongdp = new DatagramPacket(s1,s1.length,ip,port);
                        // 发送
                        ds.send(fasongdp);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(runnable1).start();
        // 释放资源
        //ds.close();

    }
}
